package me.ezitku.base.Socket

import com.pawegio.kandroid.runOnUiThread
import com.ug_project.Async.runASync
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket

/**
 *
 * Created by yurqi on 2017/5/31.
 *
 */

var socketServer = ServerSocket(SocketConst.DEFAULT_TCP_PORT)

fun createTcpSocket(action: TCP.(Socket) -> Unit) {
    var tcp = TCP()
    runASync {
        while (true) {
            val socket = socketServer.accept()
//            runOnUiThread {
//                runASync {
                    action.invoke(tcp, socket)
//                }
//            }
        }
    }
}

//fun createTcpSocketWhile(action: TCP.(Socket) -> Unit) {
//    var tcp = TCP()
//    runASync {
//        while (true) {
//            val socket = socketServer.accept()
//            runOnUiThread {
//                runASync {
//
//                    action.invoke(tcp, socket)
//                }
//            }
//        }
//    }
//}


fun connectTcpSocket(ipAddress: String, timeOut: Int = 5000, action: (Socket) -> Unit) {
    runASync {
        var socket = Socket()
        socket.connect(InetSocketAddress(ipAddress, SocketConst.DEFAULT_TCP_PORT), timeOut)
        action.invoke(socket)
    }
}






fun Socket.sendMessage(message: String) {
    var printer = PrintWriter(getOutputStream())
    printer.println(message)
    printer.flush()
}

fun Socket.sendBytes(message: ByteArray) {
    var out = getOutputStream()
    out.write(message)
    out.flush()


}

fun Socket.sendBytes(vararg bytes: ByteArray) {
    var bb = ByteArray(0)
    bytes.forEach { bb += it }
    var out = getOutputStream()
    out.write(bb,0,bb.size)
    out.flush()
}


val Socket.readLine: String
    get() {
        var buffered = BufferedReader(InputStreamReader(getInputStream()))
        return buffered.readLine()
    }

class TCP {

}